"""Main point of entry for dwgen.

Copyright 2015 Mattias Jakobsson

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

import argparse
import re

import pkg_resources

from dwgen.generator import generate_passphrase

__version__ = pkg_resources.get_distribution('dwgen').version
version_message = """\
%(prog)s {version}
Copyright © 2015 Mattias Jakobsson
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it under certain
conditions.
See the GNU General Pulic License version 3 or later for more details.
"""


def get_languages():
    """Return available word list languages."""
    regexp = re.compile(r'([-a-z]+).wordlist.asc$')

    def parse_entry(entry):
        match = regexp.match(entry)
        return match.group(1) if match else None

    datafiles = pkg_resources.resource_listdir('dwgen', 'data')
    return filter(None, map(parse_entry, datafiles))


def main():
    parser = argparse.ArgumentParser(
        description="Generate a passphrase using the Diceware algorithm.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        '--version',
        action='version',
        version=version_message.format(version=__version__),
    )
    parser.add_argument(
        '-n', '--wordcount', metavar='N',
        type=int, default=6,
        help="the number of words to build the passphrase from",
    )
    parser.add_argument(
        '-l', '--language', metavar='LANG',
        default='en', choices=list(get_languages()),
        help="the language to use for the words of the passphrase",
    )
    parser.add_argument(
        '-s', '--separator', metavar='SEP',
        default=' ',
        help='the separator to use between the words',
    )
    args = parser.parse_args()

    passphrase = generate_passphrase(
        args.wordcount,
        language=args.language,
        separator=args.separator
    )
    print(passphrase)
